using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using TMPro;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    // 单例模式
    public static GameManager Instance { get; private set; }

    // 游戏设置
    [Header("游戏设置")]
    public float gameDuration = 10f; // 游戏时长（秒）
    public float respawnTime = 3f; // 复活时间
    public Vector3[] teamASpawnPoints; // 队伍A出生点
    public Vector3[] teamBSpawnPoints; // 队伍B出生点
    public Color teamAColor = new Color(0.2f, 0.6f, 1f); // 蓝队颜色
    public Color teamBColor = new Color(1f, 0.2f, 0.2f); // 红队颜色

    // 游戏状态
    [Header("游戏状态")]
    public bool gameInProgress = false;
    public float gameTimeRemaining;
    private Dictionary<string, string> playerTeams = new Dictionary<string, string>(); // 玩家ID -> 队伍("A"或"B")
    private Dictionary<string, int> teamScores = new Dictionary<string, int>() { { "A", 0 }, { "B", 0 } };
    private Dictionary<string, float> playerRespawnTimers = new Dictionary<string, float>();

    // 引用
    private NetworkManager networkManager;
    private GameUI gameUI;

    void Awake()
    {
        // 单例模式
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    void Start()
    {
        networkManager = FindObjectOfType<NetworkManager>();
        gameUI = FindObjectOfType<GameUI>();
        if (gameUI == null)
        {
            Debug.LogError("未找到GameUI！请确保场景中有GameUI组件。");
        }

        // 让GameUI初始化UI状态
        if (gameUI != null)
        {
            gameUI.InitializeUI();
        }
    }

    void Update()
    {
        // 处理等待玩家状态
        if (!gameInProgress)
        {
            int playerCount = playerTeams.Count;
            if (gameUI != null)
                gameUI.UpdatePlayerCount(playerCount);

            // 当有足够玩家时开始游戏
            if (playerCount >= 2 && networkManager.isServer)
            {
                StartGameForAll();
            }
            return;
        }

        // 更新游戏计时器
        if (gameTimeRemaining > 0)
        {
            gameTimeRemaining -= Time.deltaTime;
            if (gameUI != null)
                gameUI.UpdateTimer(gameTimeRemaining);
        }
        else if (gameInProgress)
        {
            EndGame();
        }

        // 处理复活
        List<string> playersToRespawn = new List<string>();
        foreach (var kvp in playerRespawnTimers)
        {
            string playerId = kvp.Key;
            float timer = kvp.Value - Time.deltaTime;

            if (timer <= 0)
            {
                playersToRespawn.Add(playerId);
            }
            else
            {
                playerRespawnTimers[playerId] = timer;
            }
        }

        // 执行复活
        foreach (string playerId in playersToRespawn)
        {
            RespawnPlayer(playerId);
            playerRespawnTimers.Remove(playerId);
        }
    }

    // 分配玩家到队伍
    public string AssignPlayerTeam(string playerId)
    {
        // 如果已分配，返回现有队伍
        if (playerTeams.ContainsKey(playerId))
        {
            return playerTeams[playerId];
        }

        // 计算现有队伍数量
        int teamACount = playerTeams.Count(x => x.Value == "A");
        int teamBCount = playerTeams.Count(x => x.Value == "B");

        // 分配到人数较少的队伍
        string team = (teamACount <= teamBCount) ? "A" : "B";
        playerTeams[playerId] = team;

        // 返回分配的队伍
        return team;
    }

    // 获取玩家队伍
    public string GetPlayerTeam(string playerId)
    {
        if (playerTeams.ContainsKey(playerId))
        {
            return playerTeams[playerId];
        }
        return null;
    }

    // 获取队伍颜色
    public Color GetTeamColor(string team)
    {
        return team == "A" ? teamAColor : teamBColor;
    }

    // 增加队伍分数
    public void AddTeamScore(string team, int points)
    {
        if (teamScores.ContainsKey(team))
        {
            teamScores[team] += points;
            UpdateScoreUI();

            // 通过网络同步分数
            if (networkManager.isServer)
            {
                NetworkManager.NetworkMessage scoreMsg = new NetworkManager.NetworkMessage
                {
                    type = "score_update",
                    data = $"{team}:{teamScores[team]}"
                };
                networkManager.BroadcastToAll(scoreMsg);
            }
        }
    }

    // 处理玩家死亡
    public void HandlePlayerDeath(string playerId, string killerId)
    {
        // 设置复活计时器
        playerRespawnTimers[playerId] = respawnTime;

        // 如果有击杀者，增加其队伍分数
        if (!string.IsNullOrEmpty(killerId) && playerTeams.ContainsKey(killerId))
        {
            string killerTeam = playerTeams[killerId];
            AddTeamScore(killerTeam, 1);

            // 增加击杀者个人分数
            PlayerController killer = networkManager.GetPlayerById(killerId);
            if (killer != null)
            {
                killer.AddScore(1);
            }
        }
    }

    // 复活玩家
    private void RespawnPlayer(string playerId)
    {
        PlayerController player = networkManager.GetPlayerById(playerId);
        if (player == null) return;

        // 获取合适的出生点
        Vector3 spawnPoint = GetTeamSpawnPoint(playerTeams[playerId]);

        // 复活玩家
        player.Respawn(spawnPoint);

        // 通知网络
        if (networkManager.isServer)
        {
            // 发送位置更新
            NetworkManager.NetworkMessage posMsg = new NetworkManager.NetworkMessage
            {
                id = playerId,
                type = "move",
                posX = spawnPoint.x,
                posY = spawnPoint.y,
                posZ = spawnPoint.z,
                rotY = 0,
            };
            networkManager.BroadcastToAll(posMsg);

            // 发送血量更新
            NetworkManager.NetworkMessage healthMsg = new NetworkManager.NetworkMessage
            {
                id = playerId,
                type = "health",
                health = 100f
            };
            networkManager.BroadcastToAll(healthMsg);
        }
    }

    // 获取队伍出生点
    private Vector3 GetTeamSpawnPoint(string team)
    {
        if (team == "A" && teamASpawnPoints.Length > 0)
        {
            int index = Random.Range(0, teamASpawnPoints.Length);
            return teamASpawnPoints[index];
        }
        else if (team == "B" && teamBSpawnPoints.Length > 0)
        {
            int index = Random.Range(0, teamBSpawnPoints.Length);
            return teamBSpawnPoints[index];
        }

        // 默认出生点
        return new Vector3(Random.Range(-10f, 10f), 0.5f, Random.Range(-10f, 10f));
    }

    // 开始游戏
    public void StartGameForAll()
    {
        // 只在服务端执行
        if (!networkManager.isServer) return;

        gameTimeRemaining = gameDuration;
        gameInProgress = true;

        // 重置分数
        teamScores["A"] = 0;
        teamScores["B"] = 0;

        // 通知所有客户端游戏开始
        NetworkManager.NetworkMessage startMsg = new NetworkManager.NetworkMessage
        {
            type = "game_start",
            data = gameDuration.ToString()
        };
        networkManager.BroadcastToAll(startMsg);

        UpdateScoreUI();

        // 所有玩家移动到队伍出生点
        foreach (var kvp in playerTeams)
        {
            string playerId = kvp.Key;
            string team = kvp.Value;
            Vector3 spawnPoint = GetTeamSpawnPoint(team);

            PlayerController player = networkManager.GetPlayerById(playerId);
            if (player != null)
            {
                // 使用复活方法设置玩家位置
                player.Respawn(spawnPoint);
            }
        }
    }

    // 处理游戏开始消息
    public void HandleGameStart(float duration)
    {
        gameTimeRemaining = duration;
        gameInProgress = true;
    }

    // 结束游戏
    private void EndGame()
    {
        gameInProgress = false;

        // 确定获胜队伍
        string winningTeam = teamScores["A"] > teamScores["B"] ? "A" : "B";

        // 使用GameUI显示游戏结束面板
        if (gameUI != null)
        {
            gameUI.ShowGameOver(winningTeam, teamScores["A"], teamScores["B"]);
        }

        // 如果是服务器，通知所有客户端
        if (networkManager.isServer)
        {
            NetworkManager.NetworkMessage endMsg = new NetworkManager.NetworkMessage
            {
                type = "game_end",
                data = $"{winningTeam}:{teamScores["A"]}:{teamScores["B"]}"
            };
            networkManager.BroadcastToAll(endMsg);
        }

        // 5秒后重置游戏
        StartCoroutine(ResetGameAfterDelay(5f));
    }

    // 处理游戏结束消息
    public void HandleGameEnd(string winningTeam, int scoreA, int scoreB)
    {
        gameInProgress = false;
        teamScores["A"] = scoreA;
        teamScores["B"] = scoreB;

        // 使用GameUI显示游戏结束面板
        if (gameUI != null)
        {
            gameUI.ShowGameOver(winningTeam, scoreA, scoreB);
        }
    }

    // 延迟后重置游戏
    private IEnumerator ResetGameAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);

        foreach (var kvp in playerTeams)
        {
            PlayerController player = networkManager.GetPlayerById(kvp.Key);
            if (player != null)
            {
                player.isDead = false;
                player.score = 0; // 重置个人分数
                player.UpdateUI(); // 更新分数显示
            }
        }

        playerRespawnTimers.Clear();

        // 然后调用开始游戏
        StartGameForAll();
    }

    // 更新UI
    private void UpdateScoreUI()
    {
        if (gameUI != null)
        {
            gameUI.UpdateTeamScores(teamScores["A"], teamScores["B"]);
        }
    }

    // 玩家离开处理
    public void HandlePlayerDisconnect(string playerId)
    {
        if (playerTeams.ContainsKey(playerId))
        {
            playerTeams.Remove(playerId);
        }

        if (playerRespawnTimers.ContainsKey(playerId))
        {
            playerRespawnTimers.Remove(playerId);
        }
    }

    public void UpdateTeamScore(string team, int score)
    {
        // 只有客户端执行这个更新（服务器已经在本地更新过了）
        if (!networkManager.isServer && teamScores.ContainsKey(team))
        {
            teamScores[team] = score;
            UpdateScoreUI(); // 刷新UI显示
        }
    }
    public int teamAScore { get { return teamScores["A"]; } }
    public int teamBScore { get { return teamScores["B"]; } }
}